package cc.opcol.iot.server.sdk;

import cc.opcol.iot.server.server.IoTSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

public class JsTimerTask extends TimerTask {
    static Logger logger= LoggerFactory.getLogger(JsTimerTask.class);
    private String callFunction="";
    private ScriptEngine scriptEngine;
    private IoTSession session;

    public JsTimerTask(String js,ScriptEngine jsEngine,IoTSession session){
        this.callFunction=js;
        this.scriptEngine=jsEngine;
        this.session=session;
    }

    @Override
    public void run() {
        try {
            if(scriptEngine==null){
                return;
            }
            Map<String,Object> parameters=new HashMap<>();
            parameters.put("session",session);
            Invocable invocable = (Invocable) scriptEngine;
            invocable.invokeFunction(callFunction,parameters);
        }catch (Exception e){
            logger.error("",e);
        }
    }
}
